package org.itboys.shop.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.admin.entity.BusinessCenter;
import org.itboys.admin.service.BusinessCenterService;
import org.itboys.baseobject.entity.KVConfig;
import org.itboys.basetemplate.entity.Favorite;
import org.itboys.basetemplate.service.FavoriteService;
import org.itboys.commons.CommonConstants.NUM;
import org.itboys.commons.CommonConstants.StaticParam;
import org.itboys.commons.utils.tools.ImagePathUtils;
import org.itboys.commons.utils.tools.ResponseManager;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.member.service.MemberService;
import org.itboys.product.entity.Product;
import org.itboys.product.entity.ProductCategory;
import org.itboys.product.service.ProductCategoryService;
import org.itboys.product.service.ProductService;
import org.itboys.seller.entity.Seller;
import org.itboys.seller.service.SellerService;
import org.itboys.shop.dto.pro.WXProListDto;
import org.itboys.shop.dto.pro.WXShopListDto;
import org.itboys.shop.entity.ShopSeller;
import org.itboys.shop.service.ShopSellerService;
import org.itboys.shop.service.Manager.WXProManager;
import org.itboys.shop.tools.WXSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import sun.util.logging.resources.logging;

/**
 * 商品
 * @author 
 *
 */
@RestController
@RequestMapping("/wx/product")
public class WXProductController extends BaseController{
	@Autowired
	private WXProManager proManager;
	@Autowired
	private ProductService productService;
	@Autowired
	private ProductCategoryService productCategoryService;
	@Autowired
	private BusinessCenterService businessCenterService;
	@Autowired
	private SellerService sellerService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private FavoriteService favoriteService;
	@Autowired
	private ShopSellerService shopService;
	/**
	 * 跳到商品管理页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/catList")
	public ModelAndView catList(@Param("catId")Long catId,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			
			List<ProductCategory>pcats=productCategoryService.getProRootCategory();
			if (null==catId) {
				catId=pcats.get(0).getId();
			}
			final Integer catIdCopy=catId.intValue();
			List<KVConfig>presult=Lists.transform(pcats,  pcat->{
				KVConfig kvConfig=new KVConfig();
				kvConfig.setKey(String.valueOf(pcat.getId()));
				kvConfig.setValue(pcat.getName());
				if (catIdCopy==pcat.getId()) {
					kvConfig.setDesc("1");
				}else {
					kvConfig.setDesc("0");
				}
				return kvConfig;
			});
			List<ProductCategory>ccats=productCategoryService.getNormalCats(catIdCopy.longValue());
			List<KVConfig>cresult=Lists.transform(ccats, ccat->{
				KVConfig kvConfig=new KVConfig();
				kvConfig.setKey(String.valueOf(ccat.getId()));
				kvConfig.setValue(ccat.getName());
				kvConfig.setDesc(ImagePathUtils.add(StaticParam.imagePath, ccat.getLogo()));
				return kvConfig;
			});
			List<ProductCategory>rcats=productCategoryService.getRecCats(catIdCopy.longValue());
			List<KVConfig>rresult=Lists.transform(rcats, rcat->{
				KVConfig kvConfig=new KVConfig();
				kvConfig.setKey(String.valueOf(rcat.getId()));
				kvConfig.setValue(rcat.getName());
				kvConfig.setDesc(ImagePathUtils.add(StaticParam.imagePath, rcat.getLogo()));
				return kvConfig;
			});
			model.addAttribute("presult", presult);
			model.addAttribute("cresult", cresult);
			model.addAttribute("rresult", rresult);
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/pro/CatList");
	}
	@RequestMapping("/listVM")
	public ModelAndView listVM(
			@RequestParam Long catId,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			model.addAttribute("catId", catId);
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/pro/ProList");
	}
	@RequestMapping("/list")
	public ModelAndView list(
			@RequestParam Long catId,
			@Param("orderBy") Integer orderBy,//1 人气 2销量 3 新品 4 价格 升序 5价格降序
			@Param("pageNo")  Integer pageNo,
			@Param("pageSize")Integer pageSize,
//			@Param("limitMin")Integer limitMin,
//			@Param("limitMax")Integer limitMax,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		model.addAttribute("orderBy", orderBy);
		ProductCategory cat=productCategoryService.getById(catId);
		switch (cat.getType()) {
		case 1:
			getProList(orderBy,catId, pageNo, pageSize, request, model);
			return new ModelAndView("/pro/ProList");
		default:
			try {
				response.sendRedirect("/wx/shop/shopList?type="+cat.getType()+"&pageNo"+pageNo+"&pageSize="+pageSize);
			} catch (IOException e) {
				logger.error("",e);
			}
			return null;
		}
		
		
	}
	private void getProList(Integer orderBy,Long catId, Integer pageNo, Integer pageSize, HttpServletRequest request, Model model) {
		try {
			
			Map<String, Object>param=Maps.newHashMap();
			if (null==orderBy) {
				orderBy=1;
			}
			switch (orderBy) {
			case 1:
				param.put("orderByKey", "-hitRate");
				break;
			case 2:
				param.put("orderByKey", "-soldCount");
				break;
			case 3:
				param.put("orderByKey", "-ct");
				break;
			case 4:
				param.put("orderByKey", "price");
				break;
			case 5:
				param.put("orderByKey", "-price");
				break;
			default:
				break;
			}
			param.put("pageNo", pageNo);
			param.put("pageSize",null==pageSize?1000:pageSize);
			param.put("categoryId", catId);
			param.put("centerId",WXSession.getMember(request).getCenterId());
//			switch (orderBy) {
//			case "SP":
//				
//				break;
//
//			default:
//				break;
//			}
			List<Product>pros=productService.listWithPaging(param);
			List<WXProListDto>result=Lists.transform(pros, product->{
				return proManager.getWXProListDto( product);
			});
			model.addAttribute("pros", result);
		} catch (Exception e) {
			logger.error("",e);
		}
	}
	@RequestMapping("/detail")
	public ModelAndView detail(
			@RequestParam Long proId,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			Product product=productService.getById(proId);
			if(product.getSellerId() == 0) {
				BusinessCenter center = businessCenterService.getById(product.getCenterId());
				model.addAttribute("weixinId", center.getWeixinId());
			} else {
				Seller seller = sellerService.getById(product.getSellerId());
				BusinessCenter center = businessCenterService.getById(seller.getCenterId());
				model.addAttribute("weixinId", center.getWeixinId());
			}
			model.addAttribute("pro", proManager.getWXProDetailDto(product));
			//更新点击率
			productService.update(proId, "hitRate", null==product.getHitRate()?1:product.getHitRate()+1);
			Member member = (Member)request.getSession().getAttribute("user");
			Long memberId = member.getId();
			Map<String,Object> param = new HashMap<>();
			param.put("memberId", memberId);
			param.put("objId",proId);
			param.put("type", product.getProductType());
			Favorite favorite = favoriteService.getFirst(param);
			
			//商品是否被收藏	0：收藏	1：取消收藏
			Integer isCollect = 1; 
			if(favorite!=null){
				 isCollect = favorite.getIsDeleted();
			}
			model.addAttribute("isCollect", isCollect);
			
		} catch (Exception e) {
			logger.error("",e);
		}
		
		return new ModelAndView("/pro/ProDetail");
	}
	@RequestMapping("/detail_ms")
	public ModelAndView detail_ms(
			@RequestParam Long proId,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			Product product=productService.getById(proId);
			model.addAttribute("pro", proManager.getWXProDetailDto(product));
		} catch (Exception e) {
			logger.error("",e);
		}
		return new ModelAndView("/pro/ProDetail");
	}

	@RequestMapping("/more")
	public ModelAndView more(HttpServletRequest request, HttpServletResponse response,Model model) {
		Member member = (Member)request.getSession().getAttribute("user");
		Map<String, Object>param=Maps.newHashMap();
		param.put("pageNo", 1);
		param.put("pageSize", 20);
		param.put("centerId",member.getCenterId());
		List<Product>pros=productService.listWithPaging(param);
		List<WXProListDto>result=Lists.transform(pros, product->{
			return proManager.getWXProListDto( product);
		});
		model.addAttribute("pros", result);
		return new ModelAndView("/pro/ProList");
	}
	
	
	@RequestMapping("/recPros")
	public void recPros(@Param("catId") Long catId,
			@Param("pageSize")Integer pageSize,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		Member member = (Member)request.getSession().getAttribute("user");
		Map<String, Object>param=Maps.newHashMap();
		param.put("pageNo", 1);
		if (null==pageSize) {
			pageSize=4;
		}
		param.put("pageSize", pageSize);
		param.put("centerId",member.getCenterId());
		param.put("productType", 1);
		param.put("orderByKey", "-soldCount,-ct");
		param.put("deleted",false);
		if (null!=catId) {
			param.put("categoryId",catId);	
		}
		List<Product>pros=productService.listWithPaging(param);
		List<WXProListDto>result=Lists.transform(pros, product->{
			return proManager.getWXProListDto( product);
		});
		ResponseManager.normalResult(result, response);
	}
	@RequestMapping("/search")
	public ModelAndView search(
			@Param("keyword")String keyword,
			@Param("pageNo")Integer pageNo,
			@Param("pageSize")Integer pageSize,
			HttpServletRequest request, HttpServletResponse response,Model model) {
		try {
			model.addAttribute("keyword", keyword);
			if (StringUtils.isBlank(keyword)) {
				return new ModelAndView("/weixin/search_pro");
			}
				List<Product>pros=Lists.newArrayList();
				Map<String, Object>param=Maps.newHashMap();
				param.put("contains:name", keyword);
				param.put("productType", 1);
				if (pageNo!=null&pageSize!=null) {
					
					param.put("pageNo", pageNo);
					param.put("pageSize", pageSize);
					pros=productService.listWithPaging(param);
				}else {
					pros=productService.list(param);
				}
				if (pros.size()>0) {
					List<WXProListDto>result=Lists.transform(pros, product->{
						return proManager.getWXProListDto( product);
					});
					model.addAttribute("pros", result);
					return new ModelAndView("/weixin/search_pro");
				}
				//如果产品列表为空，搜索店铺
				List<ShopSeller>sellers=Lists.newArrayList();
				param.clear();
				param.put("contains:shopName", keyword);
				if (pageNo!=null&pageSize!=null) {
					param.put("pageNo", pageNo);
					param.put("pageSize", pageSize);
					sellers=shopService.listWithPaging(param);
				}else {
					sellers=shopService.list(param);
				}
				List<WXShopListDto>result=sellers.stream().map(s->{
					WXShopListDto dto=new WXShopListDto();
					dto.setShopId(s.getId());
					dto.setImage(ImagePathUtils.add(StaticParam.imagePath, s.getMainImg()));
					dto.setName(s.getShopName());
					dto.setPrice(NUM.DF_00.format(shopService.getMinPrice(s.getId())/100));
					dto.setAdvantageDesc(s.getAdvantageDesc());
					return dto;
				}).collect(Collectors.toList());
				model.addAttribute("shops", result);
				return new ModelAndView("/weixin/search_shop");
		} catch (Exception e) {
			logger.error("",e);
		}
		return null;
	}
}
